using micromsg;
using MicroMsg.Common.Event;
using MicroMsg.Common.Utils;
using MicroMsg.Protocol;
using MicroMsg.Storage;
using System;
namespace MicroMsg.Scene
{
	public class NetSceneGetPSMImg : NetSceneBaseEx<GetPSMImgRequest, GetPSMImgResponse, GetPSMImgRequest.Builder>
	{
		private const string TAG = "NetSceneGetPSMImg";
		private const int MAX_TIMES = 10;
		private string mImgUrl;
		private uint mImgTotalLenth;
		private uint mStartPos;
		private byte[] mImgbuf;
		private uint mTimesToServer;
		public bool doScene(string strUrl)
		{
			Log.smethod_4("NetSceneGetPSMImg", "doscene in， strUrl =" + strUrl);
			if (string.IsNullOrEmpty(strUrl))
			{
				return false;
			}
			this.mImgUrl = strUrl;
			this.mImgTotalLenth = 0u;
			this.mStartPos = 0u;
			this.mTimesToServer = 0u;
			this.mImgbuf = null;
			this.doSceneEx();
			return true;
		}
		private bool doSceneEx()
		{
			Log.smethod_4("NetSceneGetPSMImg", "dosceneEx in,startPos = " + this.mStartPos);
			base.beginBuilder();
			this.mBuilder.BaseRequest = NetSceneBase.makeBaseRequest(0);
			this.mBuilder.URL = this.mImgUrl;
			this.mBuilder.Offset = this.mStartPos;
			this.mSessionPack.mConnectMode = 2;
			this.mSessionPack.mCmdUri = "/cgi-bin/micromsg-bin/getpsmimg";
			base.endBuilder();
			this.mTimesToServer += 1u;
			return true;
		}
		protected override void onFailed(GetPSMImgRequest request, GetPSMImgResponse response)
		{
			Log.smethod_4("NetSceneGetPSMImg", "onFailed in");
		}
		protected override void onSuccess(GetPSMImgRequest request, GetPSMImgResponse response)
		{
			Log.smethod_4("NetSceneGetPSMImg", "onSuccess in" + response.TotalLength);
			RetConst ret = (RetConst)response.BaseResponse.Ret;
			if (ret != RetConst.MM_OK)
			{
				Log.smethod_1("NetSceneGetPSMImg", "get GetPSMImgRequest failed");
				return;
			}
			if (response.TotalLength == 0u)
			{
				Log.smethod_1("NetSceneGetPSMImg", "get GetPSMImgRequest failed, response.TotalLen = " + response.TotalLength);
				return;
			}
			if (this.mTimesToServer > 10u)
			{
				Log.smethod_1("NetSceneGetPSMImg", "reach the max times, mTimesToServer = " + this.mTimesToServer);
				return;
			}
			this.mImgTotalLenth = response.TotalLength;
			if (this.mImgbuf == null || (long)this.mImgbuf.Length != (long)((ulong)response.TotalLength))
			{
				this.mImgbuf = new byte[this.mImgTotalLenth];
			}
			Buffer.BlockCopy(response.Data.Buffer.ToByteArray(), 0, this.mImgbuf, (int)this.mStartPos, response.Data.Buffer.ToByteArray().Length);
			this.mStartPos += (uint)response.Data.Buffer.ToByteArray().Length;
			if (this.mStartPos < this.mImgTotalLenth)
			{
				this.doSceneEx();
				return;
			}
			string fileName = StorageIO.getBannerPath() + "/banner.jpg";
			StorageIO.writeToFile(fileName, this.mImgbuf, false);
			EventCenter.postEvent(EventConst.ON_NETSCENE_GET_PSM_IMG_SUCCESS, this.mImgUrl, null);
		}
	}
}
